<template>
	<view class="content">
		<form @submit="formSubmitInfoTap">
			<view class="gz-list">
				<view class="gz-list-item block">
					<view class="gz-list-left">
						<image :src="data.headPic ? data.headPic : '../../static/new/user/default-head.png'" style="width: 132rpx;height: 132rpx;border-radius: 50%;"></image>
					</view>
					<view class="gz-list-right">
						<button plain open-type="chooseAvatar" @chooseavatar="onChooseAvatar" style="font-size: 28rpx;border: none;width: initial;">
							点击修改头像
						</button> 
						<image src="@/static/new/arrow-right.png" />
					</view>
				</view>
				<view class="block">
					<view class="gz-list-item">
						<view class="gz-list-left">
							<view class="title"><text>昵称</text></view>
						</view>
						<view class="gz-list-right">
							<input type="nickname" placeholder="请输入昵称" name="nickName" :value="data.nickName" placeholder-style="font-size: 28rpx; color: #a3a3a3;">
						</view>
					</view>
					<view class="gz-list-item">
						<view class="gz-list-left">
							<view class="title"><text>性别</text></view>
						</view>
						<view class="gz-list-right">
							<picker @change="bindPickerChange" name="sex" :value="data.sex" :range="data.sexOptions">
								<view class="uni-input">
									<text :style="{ color: data.sex === 0 ? '#a3a3a3' : '#666' }">{{data.sexOptions[data.sex]}}</text>
								</view>
							</picker>
							<image src="@/static/new/arrow-right.png" />
						</view>
					</view>
					<view class="gz-list-item">
						<view class="gz-list-left">
							<view class="title"><text>生日</text></view>
						</view>
						<view class="gz-list-right">
							<picker mode="date" name="birthday" :value="data.birthday" :start="startDate" :end="endDate" @change="bindDateChange">
								<view class="uni-input" :style="{ color: data.birthday ? '#666' : '#a3a3a3' }">{{data.birthday || '请选择生日'}}</view>
							</picker>
							<image src="@/static/new/arrow-right.png" />
						</view>
					</view>
					<!-- font-size: 18rpx; -->
				</view>

				<view class="block">
					<view class="title" style="padding: 10rpx 30rpx;font-weight: 400;font-size32rpx;background-color: rgba(211,211,211,.3);">
						不可修改数据
					</view>
					<view class="gz-list-item">
						<view class="gz-list-left">
							<view class="title"><text>真实姓名</text></view>
						</view>
						<view class="gz-list-right">
							<text v-if="data.realName" class="uni-input">{{ nameMask(data.realName) }}</text>
						</view>
					</view>
					<view v-if="bindMchs.length" class="gz-list-item">
						<view class="gz-list-left">
							<view class="title"><text>商户号</text></view>
						</view>
						<view class="gz-list-right">
							<text class="uni-input">{{ bindMchs.map(item => item.mchNo).join('，') }}</text>
						</view>
					</view>
					<view class="gz-list-item">
						<view class="gz-list-left">
							<view class="title"><text>手机号码</text></view>
						</view>
						<view class="gz-list-right">
							<text v-if="data.phone" class="uni-input">{{ data.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') }}</text>
						</view>
					</view>
					
					<view class="gz-list-item">
						<view class="gz-list-left">
							<view class="title"><text>归属网点</text></view>
						</view>
						<view class="gz-list-right">
							<text class="uni-input">{{ data.gswdAgentName }}</text>
						</view>
					</view>
				</view>
			</view>
			
			<button plain class="gz-button" form-type="submit" size="large">确认</button>
		</form>
	</view>
</template>

<script setup>
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { ref, reactive, computed, defineProps, getCurrentInstance } from 'vue'
	import { $fansUpdate, $fansDetail, $getUserWxPhone, $ossFilesForm } from '@/http/apiManager.js'
	import appConfig from '../../config/appConfig';
	import storageManage from '@/util/storageManage.js'
	
	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties

	// 按钮loading
	const btnLoading = reactive({
		headPicLoading: false,
		phoneLoading: false,
	})
	
	const data = reactive({
		headPic: '',
		sex: 0,
		sexOptions: ['未知', '男', '女'],
	})
	
	// 是否绑定商户
	const bindMchs = ref([])
	
	onLoad(async (options) => {
		if(storageManage.MCHS_CC()?.length){	// 获取本地缓存商户信息
			bindMchs.value = storageManage.MCHS_CC()
		}
		const { bizData } = await $fansDetail()
		Object.assign(data, bizData)
	})
	/**
	 * 姓名脱敏
	 */
	function nameMask(name) {
		if (name) {
			var len = name.length;
		if (len > 1) {
			return name = name.charAt(0) + '*'.repeat(len - 1);
		} else {
			return name;
		}
		} else {
			return '';
		}
	}
	
	/**
	 * 用户授权头像
	 */
	function onChooseAvatar({ detail }){
		if(detail.avatarUrl){
			uni.getFileSystemManager().getFileInfo({
				filePath: detail.avatarUrl,
				success({ size }){
					$ossFilesForm({
						bizType: 'user',
						sourceFileName: getFileName(detail.avatarUrl),
						sourceFileSize: size
					}).then(({ bizData }) => {
						let url = bizData.formActionUrl
						let ossFileUrl = bizData.ossFileUrl
						// 调用图片上传方法
						uploadImg(detail.avatarUrl, url, bizData.formParams, ossFileUrl)
					
					})
				}
			})
		}
	}
	function uploadImg(tempFilePath, url, formParams, ossFileUrl) {
	
		const token = storageManage.token()
	
		uni.showLoading({ title: '上传中...' });
		//循环上传图片
		
		uni.uploadFile({
			url: url,
			filePath: tempFilePath,
			name: 'file',
			header: {
				'Content-Type':'multipart/form-data'
			},
			formData: formParams,
			// 代表完成的函数 注：此处可以传入三个函数  success （成功）/ fail（失败） / complete （完成）
			complete(res) {
				uni.hideLoading()
				if (res.statusCode != 200 && res.statusCode != 204) {
					$infoBox.toast('请求失败，请重试')
					return
				}
				data.headPic = ossFileUrl
				btnLoading.headPicLoading = false
			}
		})
	}
	/**
	 * 获取文件名称
	 */
	function getFileName(name){
	  if(!name){
	    return name
	  }
	  return name.substring(name.lastIndexOf('/') + 1)
	}
	

	function bindPickerChange(e) {
		data.sex = +e.detail.value
	}
	// 生日相关函数
	function getDate(type) {
		const date = new Date();
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();

		if (type === 'start') {
			year = year - 60;
		} else if (type === 'end') {
			year = year
		}
		month = month > 9 ? month : '0' + month;
		day = day > 9 ? day : '0' + day;
		return `${year}-${month}-${day}`;
	}
	const startDate = computed(() => {
		return getDate('start')
	})
	const endDate = computed(() => {
		return getDate('end')
	})

	function bindDateChange(e) {
		data.birthday = e.detail.value
	}

	// 提交保存--------------------------------------
	const formSubmitInfoTap = ({ detail }) => {
		getApp().preventActive(()=>{
			Object.assign(data,detail.value)
			// 校验数据
			if (!data.headPic) {
				$infoBox.toast('请上传头像！')
				return
			}
			if (!data.nickName) {
				$infoBox.toast('请输入您的昵称！')
				return
			}
			// if (!data.phone) {
			// 	$infoBox.toast('请输入您的手机号码！')
			// 	return
			// }
			$fansUpdate({ ...detail.value, headPic: data.headPic }).then(res => {
				$infoBox.successToast("更新成功", { duration: 2000, mask: true })
				storageManage.userInfo(data)
				// 通讯我的页面更新用户信息
				uni.$emit('USER_REFRESH_USERINFO')
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					})
				}, 2000)
			})
		})
	}
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		min-height: 100vh;
		background: #F7F8FB;
		padding: 24rpx;
		box-sizing: border-box;
		overflow: hidden;

		.store-list {
			width: 100%;
			height: 100%;
		}

		.gz-list {

			&::after,
			&::before {
				content: '';
				width: 0;
				height: 0;
				background-color: transparent;
			}


			.gz-list-item {

				align-items: center;
				padding: 30rpx;

				&::after {
					content: '';
					width: 0;
					height: 0;
					background-color: transparent;
				}

				.gz-list-left {
					min-width: 20%;
					flex-shrink: 0;
					.title {
						text {
							font-size: 32rpx;
							color: #333333;
						}
					}

					.number {
						text {
							font-size: 22rpx;
							color: #aaa;
						}
					}
				}

				.gz-list-right {
					display: flex;
					align-items: center;
					gap: 20rpx;

					button, text {
						text-align: right;
						font-size: 28rpx;
						color: #a3a3a3;
					}

					image {
						width: 14rpx !important;
						height: 24rpx !important;
						margin-left: 20rpx;
					}

					.switch {
						width: 50rpx;
						height: 100%;
						margin-left: 10rpx;
					}

					button {
						height: 50rpx;
						border-radius: 25rpx;
						display: inline-block;
						line-height: 50rpx;
						font-size: 12px;
						padding: 0;
						width: 220rpx;
						margin-left: 20rpx;
					}

					input {
						width: 100%;
						text-align: right;
						font-size: 28rpx;
						color: #666;
					}

					image {
						margin-left: 10rpx;
						width: 50rpx;
						height: 50rpx;
					}

					.number-text {
						color: #9ea5b3;
					}
				}
			}

			.block {
				border-radius: 20rpx;
				overflow: hidden;
				background-color: #FFFFFF;
				margin-bottom: 24rpx;
				position: relative;

				.gz-list-item {
					position: relative;

					&::after {
						content: '';
						display: block;
						position: absolute;
						bottom: 0;
						width: calc(100% - 60rpx);
						height: 2rpx;
						background-color: #f0f0f0;
					}
				}
			}

			.switch-item {
				padding: 0 30rpx;
				align-items: center;
				height: 110rpx;
			}
		}

		.gz-button {
			width: 100%;
			height: 90rpx;
			height: 100rpx;
			background: #FFFFFF;
			border-radius: 50rpx;
			border: 2rpx solid #DADADA;
			border-radius: 50rpx;
			margin: 80rpx auto 0;

			display: flex;
			justify-content: center;
			align-items: center;
			font-weight: 500;
			font-size: 32rpx;
			color: #333333;
		}
	}

	.swiper-item {
		display: flex;
		justify-content: space-between;
		flex-direction: column;
		width: 600rpx;
		height: 320rpx;
		background: #fff;
		border-radius: 20rpx;
		overflow: hidden;
		box-sizing: border-box;
		padding: 20rpx;

		.title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin: 30rpx auto 50rpx auto;

			text {
				font-size: 26rpx;
				color: #3981FF;
			}

			image {
				margin-right: 20rpx;
				width: 30rpx;
				height: 30rpx;
			}

			.money {
				text {
					font-size: 33rpx;
					font-weight: 400;
					color: #000;
				}
			}
		}

		.buttons {
			display: flex;
			justify-content: space-between;

			.cancel,
			.confirm {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 270rpx;
				height: 90rpx;
				border-radius: 10rpx;

				text {
					font-size: 30rpx;
				}
			}

			.cancel {
				border: 2rpx solid #c5c7cc;

				text {
					color: #808080;
				}
			}

			.confirm {
				background: #3981FF;
				color: #fff;
			}
		}
	}

	.font {
		font-family: "PingFang SC Medium";
		font-weight: 500;
		font-size: 28rpx;
		text-align: left;
		color: #000;
	}

	:deep(.input-arrow) {
		display: none !important;
	}

	:deep(.input-value-border) {
		border: none !important;
		height: initial !important;
	}

	:deep(.input-placeholder) {
	}

	.uni-input {
		font-size: 28rpx;
	}
</style>